"nodejs";
// const http = require("http"); // 引入koa
const Koa = require("koa"); // 引入koa
const Router = require("koa-router"); // 引入koa-router
const service = require("./service");
const koaBody = require("koa-body");
/* -------------------------------------------------------------------------- */
const app = new Koa(); // 创建koa应用
const router = new Router(); // 创建路由，支持传递参数
app.use(
  koaBody({
    multipart: true, // 允许上传多个文件
    jsonLimit: 5 * 1024 * 1024, // 文件上传大小
  })
);

function setActionMappings(action) {
  return async function (ctx) {
    return await service[action](ctx);
  };
}

const actionMappings = {
  ChangeAgePic: setActionMappings("ChangeAgePic"),
  SwapGenderPic: setActionMappings("SwapGenderPic"),
  FaceCartoonPic: setActionMappings("FaceCartoonPic"),
  MorphFace: setActionMappings("MorphFace"),
  QueryFaceMorphJob: setActionMappings("QueryFaceMorphJob"),
  SegmentPortraitPic: setActionMappings("SegmentPortraitPic"),
  DetectBodyJoints: setActionMappings("DetectBodyJoints"),
  DetectBody: setActionMappings("DetectBody"),
};

router
  .get("/", async (ctx) => {
    console.log("get /");

    ctx.type = "html";
    ctx.body = "<h1>hello world!</h1>";
  })
  .get("/exit", async (ctx) => {
    console.log("get /exit");
    ctx.type = "html";
    ctx.body = "<h1>exit!</h1>";
    setTimeout(function () {
      console.error("接收到exit请求, 主动停止进程");
      process.kill(process.pid, "SIGTERM");
      // console.log("程序停止");
      // server.close();
      // throw new Error("exit exit exit");
    }, 200);
  })
  .post("/", async (ctx) => {
    console.log("post /");
    let action = ctx.request.body.action;
    console.log(`action = ${action}`);
    if (!action || !actionMappings[action]) {
      ctx.type = "html";
      ctx.body = "<h1>unknown action!</h1>";
      return false;
    }

    let data = await actionMappings[action](ctx);
    if (!data) {
      ctx.type = "html";
      ctx.body = "<h1>hello world!</h1>";
    } else {
      ctx.type = "json";
      ctx.body = data;
    }
  });

// 调用router.routes()来组装匹配好的路由，返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件，当发送了不符合的请求时，会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
app.use(router.routes());
app.use(
  router.allowedMethods({
    throw: true, // 抛出错误，代替设置响应头状态
    notImplemented: () => "不支持当前请求所需要的功能",
    methodNotAllowed: () => "不支持的请求方式",
  })
);

// 启动服务监听本地端口
let port = "34567";
app.listen(port, () => {
  console.log("应用已经启动，http://localhost:" + port);
});

// let server = http.createServer(app.callback()).listen(port);
